package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.UUID;
import org.apache.http.Header;
import org.json.JSONException;

/**
 * 添加最新公告
 *
 * @author wu
 */
@SuppressWarnings("deprecation") public class PublishAnnounceMentFragment
    extends PublishAnnounceBaseFragment {

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 设置返回图标
    setTitleCustom(R.string.publishAnnounce);

    mId = UUID.randomUUID().toString();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //		inflater.inflate(R.menu.menu_confirm, menu);
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override // 响应返回图标
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_save:
        if (TextUtils.isEmpty(mtvAnnounceTypePublicAnnounce.getTextContent().trim())) {
          ToastUtil.show(R.string.chooseKnowLedgeType);
        } else if (TextUtils.isEmpty(mtv_announceTitle.getTextContent().trim())) {
          ToastUtil.show(R.string.chooseAnnounceTitle);
        } else if (TextUtils.isEmpty(mtv_announceIntroduction.getTextContent().trim())) {
          ToastUtil.show(R.string.conpleteAnnounceIntro);
        } else if (TextUtils.isEmpty(mtvKeyWordsDetailPublicAnnounce.getTextContent().trim())) {
          ToastUtil.show(R.string.inputKeyWords);
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.ifSureSave);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostSave(SAVE);
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;
      case R.id.menu_item_submit:
        if (TextUtils.isEmpty(mtvAnnounceTypePublicAnnounce.getTextContent().trim())) {
          ToastUtil.show(R.string.chooseKnowLedgeType);
        } else if (TextUtils.isEmpty(mtv_announceTitle.getTextContent().trim())) {
          ToastUtil.show(R.string.chooseAnnounceTitle);
        } else if (TextUtils.isEmpty(mtv_announceIntroduction.getTextContent().trim())) {
          ToastUtil.show(R.string.conpleteAnnounceIntro);
        } else if (TextUtils.isEmpty(mtvKeyWordsDetailPublicAnnounce.getTextContent().trim())) {
          ToastUtil.show(R.string.inputKeyWords);
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.cannotEdit);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostSave(SAVE_CHECK);
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;
      default:
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave(final int requestCode) {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.URL_SAVE_ANNOUNCE;
    RequestParams params = new RequestParams();
    params.put("id", mId);//记录id

    params.put("type", "mobile");
    params.put("docKindName", mKnowledgeName);// 公文类别
    params.put("docKindCode", mKnowledgeCode);// 公文类别编码
    if (!TextUtils.isEmpty(mtvKeyWordsDetailPublicAnnounce.getTextContent().trim())) {
      params.put("docKeyWords", mtvKeyWordsDetailPublicAnnounce.getTextContent().trim());// 关键字
    }
    params.put("noticeTitle", mtv_announceTitle.getTextContent().trim());// 公告标题
    params.put("dataNoticeBegin", "");// 开始时间
    params.put("dataNoticeEnd", "");// 结束时间
    //		if (mStartTime != null) {
    //			params.put("dataNoticeBegin", mStartTime);// 开始时间
    //		} else {
    //			String start=MyDateUtil.getBeforeThreeMonth();
    //			params.put("dataNoticeBegin", start);// 开始时间
    //		}
    //
    //		if (mEndTime != null) {
    //			params.put("dataNoticeEnd", mEndTime);// 结束时间
    //		} else {
    //			String end=MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE);
    //			params.put("dataNoticeEnd", end);// 结束时间
    //		}
    params.put("ckEditor", mtv_announceIntroduction.getTextContent().trim());// 公告内容
    //params.put("docContentDesc", mtv_announceIntroduction.getTextContent().toString().trim());// 公告内容
    if (!TextUtils.isEmpty(mtvOhtersRemark.getTextContent().trim())) {
      params.put("remark", mtvOhtersRemark.getTextContent().trim());// 备注
    }
    params.put("memberCode", mMemberCode);// 会员编码
    params.put("dataStatus", "new");// 数据状态
    params.put("systemIndex", "5");// 数据状态

    params.put("ifRemindReader", "F");// 是否提示阅读人
    if (mFilePath != null) {
      InputStream myInputStream = null;
      try {
        myInputStream = new FileInputStream(mFilePath);
      } catch (FileNotFoundException e) {
        LogUtil.e("errorLog==", e);
        Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      }
      if (myInputStream != null) {
        String name = mFilePath.substring(mFilePath.lastIndexOf("/"), mFilePath.length());
        params.put("aFile", myInputStream, name);
      }
    }
    LogUtil.e("params===" + params);
    DefaultAsyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {

      @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(new String(arg2), SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          if (SAVE == requestCode) {
            ToastUtil.show(message);
            MyUtils.dismissDialog();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else if (SAVE_CHECK == requestCode) {
            volleyPostSubmit();
          }
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
        MyUtils.show(getActivity(), R.string.save_failure);
        LogUtil.e("arg0===" + arg0);
      }
    });
  }

  /**
   * 启动流程
   */
  private void volleyPostSubmit() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ANNOUNCE_START);
    HashMap<String, String> params = new HashMap<>();
    params.put("isList", "1");
    params.put("id", mId);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.startFolwFail);
        LogUtil.e("arg0===" + arg0);
      }
    });
    LogUtil.e("params===" + params);
  }
}
